package com.happy.cat.project.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.happy.cat.common.utils.BeanTools;
import com.happy.cat.common.utils.StringUtils;
import com.happy.cat.common.utils.poi.ExcelUtil;
import com.happy.cat.framework.web.controller.BaseController;
import com.happy.cat.framework.web.domain.AjaxResult;
import com.happy.cat.framework.web.page.TableDataInfo;
import com.happy.cat.project.system.domain.*;
import com.happy.cat.project.system.domain.vo.IdParam;
import com.happy.cat.project.system.domain.vo.UserInfoItemVo;
import com.happy.cat.project.system.domain.vo.UserUpdateByNumbers;
import com.happy.cat.project.system.service.*;
import com.happy.cat.framework.aspectj.lang.annotation.Log;
import com.happy.cat.framework.aspectj.lang.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户注册的账号Controller
 *
 * @author verne
 * @date 2020-08-04
 */
@AllArgsConstructor
@RestController
@RequestMapping("/system/catUserAccount" )
@Api("用户注册的账号 API")
public class UserAccountController extends BaseController {

    private final IUserAccountService iUserAccountService;

    private final IUserImAuthorityService imAuthorityService;

    private final IUserGiftDetailService iUserGiftDetailService;

    private final ICatGiftService giftService;

    private final IUserRealAuthService realAuthService;

    private final IUserBalancePetValueDetailService balancePetValueDetailService;

    private final IUserOrderService orderService;
    private final IUserCardVoucherService voucherService;
    private final IUserLoginLogService logService;
    private final IUserOfficialAccountService userOfficialAccountService;
    private final IUserApplyWithdrawService userApplyWithdrawService;

    /**
     * 查询用户注册的账号列表
     */
    @GetMapping("/giftList/{id}")
    public AjaxResult giftList (@PathVariable("id" ) Long id){
        List<Map<String, Object>> list = iUserGiftDetailService.groupByGiftToReceiverId(id);
        if(list.size()<=0){
            return AjaxResult.success();
        }

        Set<Long> giftIds = list.stream().map(e -> Long.parseLong(e.get("gift_id").toString())).collect(Collectors.toSet());
        Map<Long, CatGift> giftMap = giftService.listByIds(giftIds).stream().collect(Collectors.toMap(CatGift::getId, e -> e));

        List<UserGiftWall> walls = new ArrayList<>();
        list.forEach(e -> {
            UserGiftWall giftWall = new UserGiftWall();
            CatGift gift = giftMap.get(Long.parseLong(e.get("gift_id").toString()));
            giftWall.setGiftImage(gift.getGiftImg());
            giftWall.setGiftName(gift.getName());
            giftWall.setGiftNumbers(Integer.parseInt(e.get("gifts").toString()));
            giftWall.setGiftSends(Integer.parseInt(e.get("counts").toString()));
            giftWall.setGiftText(e.get("text").toString());
            walls.add(giftWall);
        });
        return AjaxResult.success(walls);
    }

    /**
     * 查询用户注册的账号列表
     */
    @ApiOperation(value = "查询用户注册的账号列表",notes = "查询用户注册的账号列表",response = TableDataInfo.class)
    @PreAuthorize("@ss.hasPermi('system:catUserAccount:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserAccount userAccount)
    {
        startPage();
        LambdaQueryWrapper<UserAccount> lqw = new LambdaQueryWrapper<UserAccount>();
        if (StringUtils.isNotBlank(userAccount.getAccountName())){
            lqw.like(UserAccount::getAccountName ,userAccount.getAccountName());
        }
        if (userAccount.getUserId() != null){
            lqw.eq(UserAccount::getUserId ,userAccount.getUserId());
        }
        if (StringUtils.isNotBlank(userAccount.getPassword())){
            lqw.eq(UserAccount::getPassword ,userAccount.getPassword());
        }
        if (userAccount.getStatus() != null){
            lqw.eq(UserAccount::getStatus ,userAccount.getStatus());
        }
        if (StringUtils.isNotBlank(userAccount.getNick())){
            lqw.eq(UserAccount::getNick ,userAccount.getNick());
        }
        if (StringUtils.isNotBlank(userAccount.getTitle())){
            lqw.eq(UserAccount::getTitle ,userAccount.getTitle());
        }
        if (userAccount.getSex() != null){
            lqw.eq(UserAccount::getSex ,userAccount.getSex());
        }
        if (userAccount.getBalance() != null){
            lqw.eq(UserAccount::getBalance ,userAccount.getBalance());
        }
        if (userAccount.getPetValueBalance() != null){
            lqw.eq(UserAccount::getPetValueBalance ,userAccount.getPetValueBalance());
        }
        if (userAccount.getLightStick() != null){
            lqw.eq(UserAccount::getLightStick ,userAccount.getLightStick());
        }
        if (StringUtils.isNotBlank(userAccount.getChannel())){
            lqw.eq(UserAccount::getChannel ,userAccount.getChannel());
        }
        if (StringUtils.isNotBlank(userAccount.getDevice())){
            lqw.eq(UserAccount::getDevice ,userAccount.getDevice());
        }
        if (StringUtils.isNotBlank(userAccount.getSignature())){
            lqw.eq(UserAccount::getSignature ,userAccount.getSignature());
        }
        if (StringUtils.isNotBlank(userAccount.getArea())){
            lqw.eq(UserAccount::getArea ,userAccount.getArea());
        }
        if (StringUtils.isNotBlank(userAccount.getUserLevel())){
            lqw.eq(UserAccount::getUserLevel ,userAccount.getUserLevel());
        }
        if (StringUtils.isNotBlank(userAccount.getAvatar())){
            lqw.eq(UserAccount::getAvatar ,userAccount.getAvatar());
        }
        if (userAccount.getIsOnline() != null){
            lqw.eq(UserAccount::getIsOnline ,userAccount.getIsOnline());
        }
        if (userAccount.getCatCode() != null){
            lqw.eq(UserAccount::getCatCode ,userAccount.getCatCode());
        }
        if (userAccount.getAge() != null){
            lqw.eq(UserAccount::getAge ,userAccount.getAge());
        }
        if (userAccount.getChannelId() != null){
            lqw.eq(UserAccount::getChannelId ,userAccount.getChannelId());
        }
        if (userAccount.getBirthDay() != null){
            lqw.eq(UserAccount::getBirthDay ,userAccount.getBirthDay());
        }
        if (StringUtils.isNotBlank(userAccount.getPhone())){
            lqw.eq(UserAccount::getPhone ,userAccount.getPhone());
        }
        lqw.orderByDesc(UserAccount::getCreateTime);
        List<UserAccount> list = iUserAccountService.list(lqw);
        return getDataTable(list);
    }

    /**
     * 导出用户注册的账号列表
     */
    @ApiOperation(value = "导出用户注册的账号列表",notes = "导出用户注册的账号列表",response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:catUserAccount:export')" )
    @Log(title = "用户注册的账号" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(UserAccount userAccount) {
        LambdaQueryWrapper<UserAccount> lqw = new LambdaQueryWrapper<UserAccount>(userAccount);
        List<UserAccount> list = iUserAccountService.list(lqw);
        ExcelUtil<UserAccount> util = new ExcelUtil<UserAccount>(UserAccount. class);
        return util.exportExcel(list, "catUserAccount" );
    }

    /**
     * 获取用户注册的账号详细信息
     */
    @ApiOperation(value = "获取用户注册的账号详细信息",notes = "获取用户注册的账号详细信息",response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:catUserAccount:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult getInfo(@PathVariable("id" ) Long id) {
        UserAccount data = iUserAccountService.getById(id);
        if(data == null){
            return AjaxResult.success(data);
        }
        if(data.getUserId() == null){
            return AjaxResult.success(data);
        }

        UserImAuthority auth = null;
        if(data.getUserId()>0){
            auth = imAuthorityService.getByUserId(data.getUserId());
        }
        if(auth == null){
            auth = new UserImAuthority();
        }
        data.setUserImAuthority(auth);



        return AjaxResult.success(data);
    }

    /**
     * 获取用户注册的账号详细信息
     */
    @GetMapping(value = "/info/{id}" )
    public AjaxResult getInfoById(@PathVariable("id" ) Long id) {
        UserAccount data = iUserAccountService.getById(id);
        if(data == null){
            return AjaxResult.success(data);
        }
        if(data.getUserId() == null){
            return AjaxResult.success(data);
        }
        UserInfoItemVo item = data.convertToItemVo();
        item.setRealAuth(realAuthService.lambdaQuery().eq(UserRealAuth::getAccountId, id).eq(UserRealAuth::getStatus, 1).one());
        item.setAmount(balancePetValueDetailService.amountByAccountId(id));
        item.setOrders(orderService.lambdaQuery().eq(UserOrder::getBookingId, id).count());
        item.setVouchers(voucherService.lambdaQuery().eq(UserCardVoucher::getAccountId,id).count());
        item.setLogs(logService.lambdaQuery().eq(UserLoginLog::getAccountId,id).count());
        item.setRooms(userOfficialAccountService.countsToAccountId(id, 1));
        item.setOnlineTimes(logService.getOnlineTimes(id));
        item.setRecharges(balancePetValueDetailService.rechargeByAccountId(id));
        item.setRechargeTime(balancePetValueDetailService.firstRechargeTime(id));
        item.setAttentionUsers(userOfficialAccountService.countsToAccountId(id, 0));
        item.setFansUsers(userOfficialAccountService.countsToFansId(id, 0));

        item.setCircles(userOfficialAccountService.countsToAccountId(id, 2));
        item.setWithdrawals(userApplyWithdrawService.countsToAccount(data.getAccountName()));
        item.setWithdrawalAmount(userApplyWithdrawService.sumToAmount(data.getAccountName()));

//        TODO
//        item.setGuards();
//        item.setGroupChats();

//        item.setIncomes(userOfficialAccountService);
//        item.setBadges();


        return AjaxResult.success(item);
    }


    /**
     * 修改数值
     */
    @ApiOperation(value = "修改用户余额数值",notes = "修改用户余额数值",response = AjaxResult.class)
    @Log(title = "修改用户余额数值" , businessType = BusinessType.INSERT)
    @PostMapping(value = "/updateByNumbers")
    public AjaxResult updateByNumbers(@RequestBody UserUpdateByNumbers userUpdateByNumbers) {
        return toAjax(iUserAccountService.updateByNumbers(userUpdateByNumbers) ? 1 : 0);
    }

    @ApiOperation(value = "修改状态",notes = "修改状态",response = AjaxResult.class)
    @Log(title = "修改状态" , businessType = BusinessType.UPDATE)
    @PostMapping(value = "/updateByStatus")
    public AjaxResult updateByStatus(@RequestBody IdParam idParam) {
        return toAjax(iUserAccountService.updateByStatus(idParam.getId(), idParam.getStatus()) ? 1 : 0);
    }


    /**
     * 新增用户注册的账号
     */
    @ApiOperation(value = "新增用户注册的账号",notes = "新增用户注册的账号",response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:catUserAccount:add')" )
    @Log(title = "用户注册的账号" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserAccount userAccount) {
        return toAjax(iUserAccountService.saveItem(userAccount) ? 1 : 0);
    }

    /**
     * 修改用户注册的账号
     */
    @ApiOperation(value = "修改用户注册的账号",notes = "修改用户注册的账号",response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:catUserAccount:edit')" )
    @Log(title = "用户注册的账号" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserAccount userAccount) {
        return toAjax(iUserAccountService.updateByItem(userAccount) ? 1 : 0);
    }

    /**
     * 删除用户注册的账号
     */
    @ApiOperation(value = "删除用户注册的账号",notes = "删除用户注册的账号",response = AjaxResult.class)
    @PreAuthorize("@ss.hasPermi('system:catUserAccount:remove')" )
    @Log(title = "用户注册的账号" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id: ids) {
            iUserAccountService.updateByStatus(id, -1);
        }
        return toAjax(1 );
    }


}
